package com.siyuan1.siyuan;

import cn.hutool.core.util.StrUtil;
import com.siyuan1.spring.SiyuanBeanPostProcessor;
import com.siyuan1.spring.SiyuanComponent;
import com.siyuan1.spring.SiyuanValue;
import org.springframework.beans.BeansException;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @className: SiyuanUserServiceBeanPostProcessor
 * @Description: TODO
 * @author: wzq
 * @date: 2022/8/24 15:54
 */
@SiyuanComponent
public class SiyuanUserServiceBeanPostProcessor implements SiyuanBeanPostProcessor {

	/**
	 * 这是针对所有bean 实例化之后指定的方法，需要自行过滤
	 *
	 * @param bean
	 * @param beanName
	 * @return
	 * @throws BeansException
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//		System.out.println("postProcessAfterInitialization   " + bean);
		try {
			for (Field field : bean.getClass().getDeclaredFields()) {
				if (field.isAnnotationPresent(SiyuanValue.class)) {
					field.setAccessible(true);
					field.set(bean, field.getAnnotation(SiyuanValue.class).value());
				}
			}
			return bean;
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//		System.out.println("postProcessBeforeInitialization   " + bean);
		if (StrUtil.equalsAnyIgnoreCase("orderService", beanName)) {
			Object proxyInstance = Proxy.newProxyInstance(SiyuanBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					System.out.println("代理方法日志");
					return method.invoke(bean, args);
				}
			});
			return proxyInstance;
		}
		return bean;
	}
}
